<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\facade\Db;
use app\common\validate\validate;
use app\common\model\User as UserModel;
use EasyWeChat\Factory;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\SignatureInvalidException;
use Firebase\JWT\BeforeValidException;

class User extends Api
{


    protected $noNeedLogin="*";
    protected $noNeedRight ="*";

    // 用户登录接口
    public function login()
    {
        // 获取请求参数
        $username = input('post.username');
        $password = input('post.password');

        // 参数验证
        $validate = Validate::rule([
            'username' => 'require',
            'password' => 'require',
        ]);

        $code =  input('post.code');
        if($code){
            //如果是用微信登陆
            $app = Factory::officialAccount(config('wechat'));
            $session = $app->oauth->getAccessToken($code);
            $openid = $session->getOpenId();
            $user = UserModel::where('openid', $openid)->find();
        }else{
            if (!$validate->check(['username' => $username, 'password' => $password])) {
                return $this->error($validate->getError());
            }
            // 查找用户
            $user = UserModel::where('username', $username)->find();
        }
        if (!$user) {
            return $this->error('用户不存在');
        }

        // 检查密码是否匹配
        if (!password_verify($password, $user->password)) {
            return $this->error('密码错误');
        }

        // 生成 API Token
        $token = \app\admin\model\User::setApiToken($user);

        // 返回成功的响应，并在 HTTP 头部返回 Token
        return response(json(["code" => 0, "msg" => "调用成功!","Authorization" => $token]))
            ->header('Authorization', 'Bearer ' . $token);
    }

    // 切换成老师登陆


}
